import common
from django.utils import simplejson as json
import form
from google.appengine.api import channel
from google.appengine.api import users
from google.appengine.ext import webapp
import logging
import model
import random

PLANNING_ROOM = "planning_room"

class IterationPlanningHandler(common.BaseRequestHandler):
    def _get(self):
        id = self.request.get('id')
        iteration = model.Iteration.get_by_id(int(id))
        if iteration.get_project().is_user_valid():
            user = users.get_current_user()
            channel_id = user.user_id() + '_' + str(random.randint(1, 10000))
            token = channel.create_channel(channel_id)
            observable = common.Observable(PLANNING_ROOM)
            observable.add_observer({user.nickname(): channel_id})
            self.write_out('iteration_planning.html', {
                          'iteration': iteration,
                          'token': token,
                          'channel_id':channel_id,
                          'story_form':form.StoryForm()
                          })
        else:
            self.not_allowed_error()

class ObserverEventHandler(webapp.RequestHandler):
    def post(self):
        observable = common.Observable(PLANNING_ROOM)
        observable.notify_observers(self.get_response())

class EditIPStoryDescriptionHandler(ObserverEventHandler):
    def get_response(self):
        story_id = self.request.get('story_id')
        text = self.request.get('description')
        story = model.Story.get_by_id(int(story_id))
        story.description = text
        story.put()
        response = {'event': 'description',
                'args': {'story_id': story.key().id(),
                'user': users.get_current_user().nickname(),
                'text': story.description}}
        return json.dumps(response)    

class AssignDeveloperHandler(ObserverEventHandler):
    def get_response(self):
        story_id = self.request.get('story_id')
        member_id = self.request.get('assigned_to')
        member = model.Member.get_by_id(int(member_id))
        story = model.Story.get_by_id(int(story_id))
        story.assigned_to = member.user
        story.put()
        response = {'event': 'assign',
                'args': {'story_id': story.key().id(),
                'assigned_to': story.assigned_to.nickname(),
                'series_hours': story.story_container.get_user_hours(),
                'user': users.get_current_user().nickname()}}
        return json.dumps(response)

class EditTimeHandler(ObserverEventHandler):
    def get_response(self):
        story_id = self.request.get('story_id')
        estimated_time = self.request.get('time')
        story = model.Story.get_by_id(int(story_id))
        story.estimated_time = float(estimated_time)
        story.put()
        response = {'event': 'time',
                'args': {'story_id': story.key().id(),
                'estimated_time': story.estimated_time,
                'series_hours': story.story_container.get_user_hours(),
                'user': users.get_current_user().nickname()}}
        return json.dumps(response)

class PriorityHandler(ObserverEventHandler):
    def get_response(self):
        story_id = self.request.get('story_id')
        priority = self.request.get('priority')
        story = model.Story.get_by_id(int(story_id))
        story.priority = priority
        story.put()
        response = {'event': 'priority',
                'args': {'story_id': story.key().id(),
                'priority': story.priority,
                'user': users.get_current_user().nickname()}}
        return json.dumps(response)

class CategoryHandler(ObserverEventHandler):
    def get_response(self):
        story_id = self.request.get('story_id')
        category = self.request.get('category')
        story = model.Story.get_by_id(int(story_id))
        story.category = category
        story.put()
        response = {'event': 'category',
                'args': {'story_id': story.key().id(),
                'category': story.category,
                'user': users.get_current_user().nickname()}}
        return json.dumps(response)

class NameHandler(ObserverEventHandler):
    def get_response(self):
        story_id = self.request.get('story_id')
        name = self.request.get('name')
        story = model.Story.get_by_id(int(story_id))
        story.name = name
        story.put()
        response = {'event': 'name',
                'args': {'story_id': story.key().id(),
                'name': story.name,
                'user': users.get_current_user().nickname()}}
        return json.dumps(response)

class CreateStory(ObserverEventHandler):
    def get_response(self):
        story = Story(self.request).story
        response = {'event': 'new_story',
                'args': {'story_id': story.key().id(),
                'name': story.name,
                'user': users.get_current_user().nickname()}}
        return json.dumps(response)

class Story():
    def __init__(self, request):
        iteration_id = request.get('iteration_id')
        name = request.get('name')
        category = request.get('category')
        priority = request.get('priority')
        estimated_time = request.get('estimated_time')
        description = request.get('description')
        assigned_to = request.get('assigned_to')
        logging.info('name: ' + name)

        member = model.Member.get_by_id(int(assigned_to))
        self.story = model.Story(
                                 story_container=model.Iteration.get_by_id(int(iteration_id)),
                                 name=name,
                                 category=category,
                                 priority=priority,
                                 assigned_to=member.user,
                                 estimated_time=float(estimated_time),
                                 description=description,
                                 opened_by=users.get_current_user())
        self.story.put()

class PostponeStoryHandler(ObserverEventHandler):
    def get_response(self):
        story_id = self.request.get('story_id')
        story_container = self.request.get('story_container')
        story = model.Story.get_by_id(int(story_id))
        old_story_container = story.story_container
        backlog_ = model.StoryContainer.get(story_container)
        story.story_container = backlog_
        story.put()
        update = not (story.story_container.key().id() == old_story_container.key().id())
        response = {'event': 'move_story',
            'args': {'story_id': story.key().id(),
            'update': update,
            'name': story.name,
            'series_hours': old_story_container.get_user_hours(),
            'user': users.get_current_user().nickname()}}
        return json.dumps(response)


class CommentStoryHandler(ObserverEventHandler):
    def get_response(self):
        id = self.request.get('story_id')
        text = self.request.get('comment')
        story = model.Story.get_by_id(int(id))
        comment = model.PlanningComment(story=story,
                                     author=users.get_current_user(),
                                     text=text)
        comment.put()
        response = {'event': 'comment',
            'args': {'story_id': story.key().id(),
            'user': comment.author.nickname(),
            'comment':comment.text}}
        return json.dumps(response)

class ChatHandler(ObserverEventHandler):
    def get_response(self):
        text = self.request.get('message')
        iteration_id = self.request.get('iteration_id')
        iteration = model.Iteration.get_by_id(int(iteration_id))
        message = model.PlanningMessage(iteration=iteration,
                              user=users.get_current_user(),
                              text=text)
        message.put()
        response = {'event': 'chat',
            'args': {'message': text,
            'user': users.get_current_user().nickname()}}
        return json.dumps(response)